package com.example.demo.http.controllers.user;

import com.example.demo.models.Activity;
import com.example.demo.models.admin.ActivityAdmin;
import com.example.demo.models.admin.ActivityAdminLog;
import com.example.demo.models.user.User;
import com.example.demo.services.system.ResultService;
import com.example.demo.services.system.UserService;
import gaarason.database.appointment.OrderBy;
import gaarason.database.appointment.Paginate;
import gaarason.database.contract.eloquent.Builder;
import gaarason.database.contract.eloquent.Record;
import gaarason.database.contract.eloquent.RecordList;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/user/activity/admin/")
public class UserActivityAdminController {
    @Resource
    Activity.Model activityModel;
    @Resource
    ActivityAdmin.Model activityAdminModel;
    @Resource
    ActivityAdminLog.Model activityAdminLogModel;
    @Resource
    User.Model userModel;

    //查询所有活动
    @GetMapping("/")
    ResultService.Result index(@RequestParam Map<String, String> params) {
        //当前管理员
        User user = UserService.getThreadInstance().getUser();
        //分页单独处理
        String page = params.get("page");
        if (Objects.isNull(page)) {
            //如果没有页数，默认为第一页
            page = "1";
        }
        //生成查询器
        Builder<Activity, Long> builder = activityModel.newQuery();
        //只允许查询自己的
        builder.where("number", user.getName());
        //放入参数
        params.forEach((key, value) -> {
            if (!Objects.isNull(key) && !key.equals("page")) {
                //要去掉page这个参数，如果还要去掉其他就直接在这里加
                if (!Objects.isNull(value)) {
                    builder.where(key, value);
                }
            }
        });

        //返回结果
        Paginate<Activity> paginate = builder.paginate(page, 15);
        //对结果进行处理
        Map<String, Object> data = new HashMap<>();
        data.put("currentPage", paginate.getCurrentPage());
        data.put("lastPage", paginate.getLastPage());
        data.put("total", paginate.getTotal());
        data.put("perPage", paginate.getPerPage());
        data.put("data", paginate.getItemList());
        ResultService.Result result = ResultService.getNormalResult();
        result.data = data;
        return result;
    }

    //获得可用的可以被发布给的管理员的名单
    @GetMapping("/getAdmin")
    ResultService.Result getAdmin(@RequestParam Map<String, String> params) {
        //当前管理员
        User user = UserService.getThreadInstance().getUser();
        //根据管理员信息获得学院
        String college = user.getCollege();
        //获得学号后，根据活动管理员表，查出可以被提交的1级人员
        RecordList<ActivityAdmin, Long> record = activityAdminModel.newQuery().where(ActivityAdmin::getCollege, college).where(ActivityAdmin::getRank, 1).orderBy(ActivityAdmin::getId, OrderBy.ASC).select(ActivityAdmin::getNumber).get();
        //根据这个人员组出一个“学号，姓名”列表
        List<Map<String, String>> list = new ArrayList<>();
        for (Record<ActivityAdmin, Long> activityAdmin : record) {
            String number = activityAdmin.getEntity().getNumber();
            Long id = activityAdmin.getEntity().getId();
            //根据学号查出这个人具体是谁
            Record<User, Long> tempUser = userModel.newQuery().where(User::getNumber, number).first();
            Map<String, String> temp = new LinkedHashMap<>();
            temp.put("id", String.valueOf(id));
            temp.put("number", number);
            if (tempUser != null) {
                temp.put("name", tempUser.getEntity().getName());
            } else {
                temp.put("name", "");
            }
            list.add(temp);
        }
        ResultService.Result result = ResultService.getNormalResult();
        result.data = list;
        return result;
    }

    //创建活动
    @PostMapping("/create")
    ResultService.Result create(@RequestParam Map<String, String> params) {
        //当前用户
        User user = UserService.getThreadInstance().getUser();
        ResultService.Result result = ResultService.getNormalResult();
        Record<Activity, Long> activity = activityModel.newRecord();
        if (Objects.isNull(params.get("admin_id"))) {
            //如果没找到管理员id，说明没有提交，直接报错
            result.code = ResultService.CLIENT_ERROR;
            result.msg = "请选择下一级管理员";
            return result;
        }
        //首先查一下下一级管理员在不在
        Record<ActivityAdmin, Long> activityAdmin = activityAdminModel.newQuery().where(ActivityAdmin::getCollege, user.getCollege()).where(ActivityAdmin::getRank, 1).find(params.get("admin_id"));
        //如果下一级管理员不在，直接打回
        if (activityAdmin == null) {
            result.code = ResultService.CLIENT_ERROR;
            result.msg = "请选择下一级管理员";
            return result;
        }
        //填充新的活动数据
        activity.getEntity().setNumber(user.getNumber());
        activity.getEntity().setTitle(params.get("title"));
        activity.getEntity().setZone(params.get("zone"));
        activity.getEntity().setType(params.get("type"));
        activity.getEntity().setContent(params.get("content"));
        activity.getEntity().setFirstImage(params.get("first_image"));
        activity.getEntity().setActivityStart(params.get("activity_start"));
        activity.getEntity().setActivityEnd(params.get("activity_end"));
        activity.getEntity().setEnrollStart(params.get("enroll_start"));
        activity.getEntity().setEnrollEnd(params.get("enroll_end"));
        activity.getEntity().setCount(Integer.valueOf(params.get("count")));
        activity.getEntity().setCollege(params.get("college"));
        activity.getEntity().setStatus(0);
        activity.getEntity().setIsOpen(0);
        activity.save();

        //创建成功后，生成一条审核消息
        Record<ActivityAdminLog, Long> activityAdminLog = activityAdminLogModel.newRecord();
        //刷新数据，获得id
        activity.refresh();
        //填充数据
        activityAdminLog.getEntity().setActivity_id(String.valueOf(activity.getEntity().getId()));
        activityAdminLog.getEntity().setNumber(user.getNumber());
        activityAdminLog.getEntity().setData("发起审核");
        activityAdminLog.getEntity().setRank("0");
        activityAdminLog.getEntity().setStatus("1");
        //结果就是发给谁审核
        activityAdminLog.getEntity().setResult(activityAdmin.getEntity().getNumber());
        activityAdminLog.save();
        return result;
    }
}
